﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Security.Cryptography;
using System.Text;

namespace TomMaton.Umbraco.AmazonS3
{
    public class S3Helper
    {
        /// <summary>
        /// Returns a new DateTime object set to the provided time
        /// but with precision limited to milliseconds.
        /// </summary>
        /// <param name="myTime"></param>
        /// <returns></returns>
        public static DateTime GetTimeStamp(DateTime myTime)
        {
            DateTime myUniversalTime = myTime.ToUniversalTime();
            DateTime myNewTime = new DateTime(myUniversalTime.Year,
                myUniversalTime.Month,
                myUniversalTime.Day,
                myUniversalTime.Hour,
                myUniversalTime.Minute,
                myUniversalTime.Second,
                myUniversalTime.Millisecond);

            return myNewTime;
        }

        /// <summary>
        /// Formats the provided time as a string limited to millisecond precision
        /// </summary>
        /// <param name="myTime"></param>
        /// <returns></returns> 
        public static string FormatTimeStamp(DateTime myTime)
        {
            DateTime myUniversalTime = myTime.ToUniversalTime();
            return myUniversalTime.ToString("yyyy-MM-dd\\THH:mm:ss.fff\\Z", System.Globalization.CultureInfo.InvariantCulture);
        }

        public static string GetSignature(string mySecretAccessKeyId, string strOperation, DateTime myTime)
        {
            Encoding myEncoding = new UTF8Encoding();

            // Create the source which is used to create the digest
            string mySource = String.Format("AmazonS3{0}{1}", strOperation, FormatTimeStamp(myTime));

            // Create a new Cryptography class using the Secret Access Key as the key
            HMACSHA1 myCrypto = new HMACSHA1(myEncoding.GetBytes(mySecretAccessKeyId));

            //Convert the source string into an array of bytes
            char[] mySourceArray = mySource.ToCharArray();

            //Convert the source to a UTF8 encoded array of bytes
            byte[] myUTF8Bytes = myEncoding.GetBytes(mySourceArray);

            // calculate the digest
            byte[] strDigest = myCrypto.ComputeHash(myUTF8Bytes);
            return Convert.ToBase64String(strDigest);
        }
    }
}
